import styles from "../../styles/ChatDialog.module.css"
import ChatBubble from "./ChatBubble"
import React, {useRef, useEffect, useState} from "react";
import ContentEditable from "react-contenteditable";
import {TextEncoder, TextDecoder} from "web-encoding"
import {Modal, Toast, ToastContainer} from "react-bootstrap";
import Image from "next/image";

const ChatDialog = (props) => {
  const {roomName, chatInfos, myName, sendMsgCallback, clearChatCallback, showMemberCallback} = props;

  const [message, setMessage] = useState("")
  const [showMenu, setShowMenu] = useState(false)
  const [menuX, setMenuX] = useState(0)
  const [menuY, setMenuY] = useState(0)
  const [showPic,setShowPic] = useState(false)
  const [picBase64,setPicBase64] = useState("")
  console.log(picBase64)

  const divRef = useRef();
  const sendPicRef = useRef()
  const sendFileRef = useRef()

  useEffect(() => {
    divRef.current.scrollTop = divRef.current.scrollHeight
  })
  useEffect(() => {
    document.addEventListener('click', hideMenu)
    return () => document.removeEventListener('click', hideMenu)
  })

  const hideMenu = () => {
    setShowMenu(false)
  }

  const onPicBubbleClick=(base64)=>{
    setPicBase64(base64)
    setShowPic(true)
  }

  const bubbleComponents = chatInfos.map(chatInfo =>
    <ChatBubble key={chatInfo.msgId} {...chatInfo} isLocal={chatInfo.senderName === myName} onClick={onPicBubbleClick}/>)

  const sendMsg = () => {
    sendMsgCallback(roomName, message)
    setMessage('')
  }

  const onRightClick = e => {
    e.preventDefault()
    console.log(roomName)
    setMenuX(e.clientX)
    setMenuY(e.clientY)
    setShowMenu(true)
  }

  const clearChatInfo = () => {
    clearChatCallback()
    setShowMenu(false)
  }

  const uploadPic = (e) => {
    const reader = new FileReader();
    const file = e.target.files[0]
    reader.readAsDataURL(file)
    reader.onload = function (e) {
      const base64Data = e.target.result
      sendMsgCallback(roomName, base64Data)
      sendPicRef.current.value = ''
    }
  }

  const uploadFile = (e) => {
    const reader = new FileReader();
    const file = e.target.files[0]
    const filename = file.name.replace(/\s*/g,"")
    const uint8array = new TextEncoder().encode(filename);
    if (uint8array.byteLength > 100) {
      alert("文件名过长")
      sendFileRef.current.value = ''
      return
    }

    reader.onload =  (e) =>{
      const fileByteBuffer = e.target.result
      if (fileByteBuffer.byteLength > 20 * 1024 * 1024) {
        alert("文件不能大于20M")
        sendFileRef.current.value = ''
        return
      }

      const byteArray = new Uint8Array(100 + fileByteBuffer.byteLength);

      byteArray.set(uint8array,0)
      byteArray.set(new Uint8Array(fileByteBuffer),100)
      sendMsgCallback(roomName, byteArray)
      sendFileRef.current.value = ''
    };
    reader.readAsArrayBuffer(file)
  }

  const position = {top: menuY, left: menuX}

  return (
    <>
      <div className={styles.dialog}>
        <div>
          {roomName}
          <div onClick={showMemberCallback}>当前成员</div>
        </div>

        <div ref={divRef} onContextMenu={onRightClick}>
          {
            bubbleComponents.length === 0 ? (
              <div style={{textAlign: 'center', color: 'gray', fontSize: '0.5pt', paddingTop: '20%'}}>暂无任何消息</div>
            ) : bubbleComponents
          }
        </div>
      </div>

      <div className={styles.tools}>
        <label htmlFor={"send-pic"}>
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor"
               className="bi bi-file-image" viewBox="0 0 16 16">
            <path d="M8.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/>
            <path
              d="M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM3 2a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v8l-2.083-2.083a.5.5 0 0 0-.76.063L8 11 5.835 9.7a.5.5 0 0 0-.611.076L3 12V2z"/>
          </svg>
          发送图片
        </label>
        <input ref={sendPicRef} id={"send-pic"} type="file" accept={"image/*"} onChange={uploadPic}/>

        <label htmlFor={"send-file"}>
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" className="bi bi-upload"
               viewBox="0 0 16 16">
            <path
              d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/>
            <path
              d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/>
          </svg>
          发送文件
        </label>
        <input ref={sendFileRef} id={"send-file"} accept={"*/*"} type="file" onChange={uploadFile}/>
      </div>

      <div className={styles.sender}>
        <ContentEditable html={message} onChange={(e) => setMessage(e.target.value)} className={styles.msg}/>
        <button className={styles.btn} onClick={sendMsg} disabled={message === ""}>发送</button>
      </div>

      {
        showMenu ? (<div className={styles.menu} style={position} onClick={clearChatInfo}>清空聊天记录</div>) : null
      }

      <Modal show={showPic}  onHide={() =>setShowPic(false)} centered={true}>
        <Modal.Body>
          <Image src={picBase64}  width={500} height={400}/>
        </Modal.Body>
      </Modal>

    </>
  )
}

export default ChatDialog
